package net.oschina.git.views;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.message.BasicNameValuePair;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.egit.core.RepositoryUtil;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import net.oschina.git.Activator;
import net.oschina.git.utils.GitUtil;
import net.oschina.git.utils.HttpUtil;
import net.oschina.git.utils.JsonUtil;
import net.oschina.git.utils.RemoteApi;
import net.oschina.git.utils.UserData;
import net.oschina.git.utils.i18n;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;

public class ConfigPushProject extends Dialog {
	private Text name;
	private Text remoteName;
	private Text desc;
	private Button isPrivate;
	private String projectName;
	private IPath projectPath;
	protected final RepositoryUtil util = org.eclipse.egit.core.Activator.getDefault()
			.getRepositoryUtil();
	/**
	 * Create the dialog.
	 * @param parentShell
	 */
	public ConfigPushProject(Shell parentShell,String name,IPath path) {
		super(parentShell);
		projectName = name;
		projectPath = path;
	}
	@Override
	protected void setShellStyle(int newShellStyle) {
		super.setShellStyle(SWT.CLOSE | SWT.MODELESS | SWT.BORDER | SWT.TITLE | SWT.RESIZE);
		setBlockOnOpen(false);
	}
	@Override
	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Share Project On GitOSC");
		shell.setImage(AbstractUIPlugin.imageDescriptorFromPlugin(Activator.getDefault().getBundle().getSymbolicName(),"$nl$/icons/oschina.ico").createImage());
	}
	/**
	 * Create contents of the dialog.
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		parent.setLayout(new GridLayout(1, false));
		
		Composite container = (Composite) super.createDialogArea(parent);
		GridLayout gridLayout = (GridLayout) container.getLayout();
		gridLayout.numColumns = 3;
		container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		
		Label lblNewLabel = new Label(container, SWT.NONE);
		lblNewLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true, 1, 1));
		lblNewLabel.setText(i18n.NewRepName+":");
		
		name = new Text(container, SWT.BORDER);
		name.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		name.setText(projectName);
		name.setEditable(false);
		
		isPrivate = new Button(container, SWT.CHECK);
		isPrivate.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		isPrivate.setText("Private");
		
		Label lblNewLabel_1 = new Label(container, SWT.NONE);
		lblNewLabel_1.setText(i18n.RemoteName+":");
		
		remoteName = new Text(container, SWT.BORDER);
		remoteName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
		
		Label lblNewLabel_2 = new Label(container, SWT.NONE);
		lblNewLabel_2.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		lblNewLabel_2.setText(i18n.Description+":");
		
		desc = new Text(container, SWT.BORDER | SWT.WRAP);
		GridData gd_desc = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
		gd_desc.heightHint = 137;
		desc.setLayoutData(gd_desc);

		return container;
	}

	/**
	 * Create contents of the button bar.
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(final Composite parent) {
		Button share = createButton(parent, IDialogConstants.NO_ID, "Share", true);
		share.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				String private_token = UserData.getValue("private_token");
				List<NameValuePair> list = new ArrayList<NameValuePair>();  
		        list.add(new BasicNameValuePair("name", remoteName.getText()));  
		        list.add(new BasicNameValuePair("description", desc.getText())); 
		        list.add(new BasicNameValuePair("private", isPrivate.getSelection()?"1":"0"));
				try {
					String responseHtml = HttpUtil.post(RemoteApi.createProject+"?private_token="+private_token, list, parent.getShell());
					if(responseHtml!=null){
						String status = JsonUtil.getJsonValueFromStr(responseHtml, "status");
						String message = JsonUtil.getJsonValueFromStr(responseHtml, "message");
						String remoteNewProject = JsonUtil.getJsonValueFromStr(responseHtml, "path_with_namespace");
						if(status!=null&&status.equals("0")){
							MessageDialog.openError(parent.getShell(), "Error", message);
						}else{			
							String remoteUrl = null;
							if(UserData.getValue("cloneType").equals("http")){
								remoteUrl = "https://"+RemoteApi.defaultHost+"/"+remoteNewProject+".git";
								String username = UserData.getValue("username");
								String password = UserData.getValue("password");
								if(!password.equals("N/A")){
									GitUtil.createRepository(projectPath.toOSString(),remoteUrl,username,password);
								}else
								    GitUtil.createRepository(projectPath.toOSString(),remoteUrl);
							}else {
								remoteUrl = "git@"+RemoteApi.defaultHost+":"+remoteNewProject+".git";
								GitUtil.createRepository(projectPath.toOSString(),remoteUrl);
							}
							util.addConfiguredRepository(new File(projectPath.toOSString()+Platform.getLocation().SEPARATOR+".git"));						
						    PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.eclipse.egit.ui.RepositoriesView");						
							MessageDialog.openInformation(parent.getShell(), "Info", "Upload successful !");
							final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
							new ProgressMonitorDialog(parent.getShell()).run(true, true, new IRunnableWithProgress() {

								@Override
								public void run(IProgressMonitor monitor)
										throws InvocationTargetException, InterruptedException {
									try {
										project.close(monitor);
										project.open(monitor);
									} catch (CoreException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
								
							});
							parent.getShell().dispose();
						}
					}
				}catch (GitAPIException e1) {
					// TODO Auto-generated catch block
					MessageDialog.openError(parent.getShell(), "Error", e1.getMessage());
				} catch (ConnectTimeoutException e1) {
					MessageDialog.openError(parent.getShell(), "Error", "Connect Timeout");
				} catch (ClientProtocolException e1) {
					// TODO Auto-generated catch block
					MessageDialog.openError(parent.getShell(), "Error", e1.getMessage());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					MessageDialog.openError(parent.getShell(), "Error", "Network Issues");
				} catch (PartInitException e1) {
					// TODO Auto-generated catch block
					MessageDialog.openError(parent.getShell(), "Error", e1.getMessage());
				} catch (InvocationTargetException e1) {
					// TODO Auto-generated catch block
					MessageDialog.openError(parent.getShell(), "Error", e1.getMessage());
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					MessageDialog.openError(parent.getShell(), "Error", e1.getMessage());
				}
			}
		});
		Button help = createButton(parent, IDialogConstants.NO_ID, "Help", false);
		help.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseUp(MouseEvent e) {
				try {
					PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser()
							.openURL(new URL(RemoteApi.helpUrl));
				} catch (PartInitException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
	}
}
